<?php


namespace App\HttpController\Admin;

use App\Model\RecordsModel;
use App\Model\TmplmsgsModel;
use App\Queue\Queue;
use App\Utility\Cache;
use App\Utility\MiniProgram;
use Carbon\Carbon;
use EasySwoole\EasySwoole\Logger;

class MessageController extends AuthController {

    public function index(){
        $request = $this->request();
        $param = $request->getRequestParam();
        if(!isset($param['applet']) || !$param['applet']){
            $param['applet'] = 'yuanyang';
        }
        $wechat = new MiniProgram($param['applet']);
        $list = $wechat->getTemplateList();
        if(isset($list['errcode']) && $list['errcode']){
            return $this->writeJson(1,null,$list['errmsg']);
        }
        $model = new TmplmsgsModel();
        foreach ($list as &$item){
            $content = explode('}}', $item['content']);
            $keyword = array();
            $keywordText = [];
            foreach ($content as $val) {
                $keyword[] = trim(substr($val, strpos($val, "{{") + 2, -5));
                $keywordText[] = trim(substr($val, 0, strpos($val, "{{")));
            }
            $form = [];
            //获取数据库对应关键词的值，进行填充返回
            $keywordForDB = $model->where('template_id', $item['template_id'])->first();
            if (!$keywordForDB) {
                //模板ID不存在，创建
                foreach ($keyword as $word) {
                    if ($word) {
                        $form[$word] = '';
                    }
                }
                $item['page'] = '';
                $item['emphasis'] = '';
                $createData = [
                    'template_id' => $item['template_id'],
                    'keywords' => [$form],
                    'page' => $item['page'],
                    'title' => $item['title'],
                    'emphasis' => $item['emphasis'],
                ];
                $model->create($createData);
            } else {
                $form = $keywordForDB['keywords'];
                $item['page'] = $keywordForDB['page'];
                $item['emphasis'] = $keywordForDB['emphasis'];
            }
            $item['form'] = $form;
            $item['keyword'] = array_filter($keyword);
            $item['keyword_text_arr'] = array_combine($item['keyword'], array_filter($keywordText));
            $item['keyword_text'] = implode(',', array_filter($keywordText));
        }
        //从redis中获取可推送的数量
        $cache = new Cache();
//        //删除openid集合中没有用的值
//        $openids = $cache->sMembers($param['applet']);
//        foreach ($openids as $item){
//            $_data = explode('*',$item);
//            if($cache->zCard($_data[1]) == 0) $cache->srem($param['applet'],$item);
//        }
        $number = $cache->scard($param['applet']);
        return $this->writeJson(0,['list'=>$list,'number' => $number]);
    }





    public function record(){
        $request = $this->request();
        $page = $request->getRequestParam('page') ?? 1;
        $applet = $request->getRequestParam('applet') ?? 'yuanyang';
        $model = new RecordsModel();
        $list = $model->where('applet',$applet)->orderBy('start_at')->paginate($page,12);
        return $this->writeJson(0,$list);
    }

    /**
     * 更新
     * @return bool
     * @throws \Throwable
     */
    public function update(){
        try{
            $request = $this->request();
            $data = $request->getRequestParam();
            $model = new TmplmsgsModel();
            $msg = $model->where('template_id', $data['template_id'])->first();
            if (!$data['template_id'] || !$msg) {
                return $this->writeJson(1,null,'数据不存在');
            }
            $data['id'] = $msg['id'];
            $model->update($data);
            return $this->writeJson(0, null, '更新成功');
        }catch (\Exception $e){
            return $this->writeJson(1,null,$e->getMessage());
        }
    }


    public function push(){
        $request = $this->request();
        $template_id = $request->getRequestParam('id') ?: 'xxx';
        $applet = $request->getRequestParam('applet') ?: 'chunqiu';
        //判断模板消息是否存在
        $msg = (new TmplmsgsModel())->where('template_id', $template_id)->first();
        if (!$msg) {
            return $this->writeJson(1,null,'数据不存在');
        }

        //删除无用的记录
        $appletModel = $this->appletFormidsModel($applet);
        $formidModel = new $appletModel;
        $formidModel->where('expires_at',time(),'<=')->delete();

        //查询重复推送并生成推送记录
        $recordModel = new RecordsModel();
        $date = date('Y-m-d',time());
        $recordInfo = $recordModel->where('template_id',$template_id)->where('created_at',$date)->first();
        if($recordInfo){
            return $this->writeJson(1,null,'该模板消息今日已推送');
        }
        $insert = ['template_id' => $template_id, 'title' => $msg['title'], 'applet' => $applet, 'created_at' => $date];
        $recordId = $recordModel->create($insert);

        //缓存当前要推送的模板消息内容3小时
        $cache = new Cache();
        $msg['record_id'] = $recordId;
        $cache->set('template_'.$applet,$msg,3*60*60);

        //开启任务-创建模板消息推送队列
        $cache->onQueue('task_push');
        $cache->push(['applet'=>$applet,'id'=>$recordId]);
        return $this->writeJson(0, null, '推送成功');
    }

    public function token(){
        $request = $this->request();
        $applet = $request->getRequestParam('applet') ?? 'yuanyang';
        $wechat = new MiniProgram($applet);
        $token = $wechat->getToken(true);
        return $this->writeJson(0, $token, '重置access_token成功');
    }
}
